import ajax from "uni-ajax";
import { loading, offlineModal } from "./helpers";
import { toast } from "../helper";
import { serialize } from "@/libs/utils";
import config from "@/config";
import store from "@/store";
import errorCode from "@/const/errorCode";

/** 请求地址 */
const baseUrl = config.baseUrl;

// create an axios instance
const service = ajax.create({
  baseURL: baseUrl, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000, // request timeout
  validateStatus: function(status) {
    return status >= 200 && status <= 500;
  },
});

// 添加请求拦截器
service.interceptors.request.use(
  (config) => {
    // 默认是有请求加载框，当传入 loading: false 时则不显示
    config.loading !== false && loading.show(config.loadingText);

    const isToken = (config.header || {}).isToken === false;
    let token = store.getters.access_token;
    if (token && !isToken) {
      config.header["Authorization"] = "Bearer " + token; // token
    }
    // headers中配置serialize为true开启序列化
    if (config.methods === "post" && config.header.serialize) {
      config.data = serialize(config.data);
      delete config.data.serialize;
    }

    // 处理get 请求的数组 springmvc 可以处理
    if (config.method === "get") {
      config.paramsSerializer = function(params) {
        return qs.stringify(params, { arrayFormat: "repeat" });
      };
    }

    if (config.data === undefined) {
      config.data = {};
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);
// 添加响应拦截器
service.interceptors.response.use(
  (response) => {
    const { statusCode, config, data = {} } = response;
    const message = data.msg || errorCode[statusCode] || errorCode["default"];
    // 隐藏请求加载框
    config.loading !== false && loading.hide();

    // 后台定义 401 针对令牌过去的特殊响应码
    if (statusCode === 401) {
      // to re-login
      store.dispatch("LogOut").then(() => {
        uni.showModal({
          content: "会话已过期，是否跳转登录页面？",
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: "/pages/login/login",
              });
            }
          },
        });
      });
      return;
    }
    if (statusCode !== 200 || data.code === 1) {
      // 当返回状态值不为 0 时，默认 toast 提示信息，当传入 toast: false 时则不显示
      config.toast !== false &&
        statusCode.code !== 0 &&
        data.code !== 0 &&
        message &&
        toast(message);
      return Promise.reject(new Error(message));
    }

    return data;
  },
  (error) => {
    // 隐藏请求加载框
    loading.hide();
    // 中断请求
    if (error.errMsg?.includes("abort")) return Promise.reject(error);
    // 没有状态码返回通常没有网络
    !error.statusCode && offlineModal();
    return Promise.reject(error);
  }
);
export default service;
